package com.frogs.ucenter.v1.service.impl.aop;

import java.math.BigDecimal;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.util.TaskActionListEmum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserRegisterTypeEnum;
import com.frogs.system.web.api.response.Response;
import com.frogs.ucenter.util.task.TaskActionMqSend;
import com.frogs.ucenter.v1.util.ApiConstants;

@Aspect
@Service(ApiConstants.VERSION+"taskAopImpl")
public class TaskAopImpl extends BaseTaskAop {
	
	private static final Logger log = LoggerFactory.getLogger(TaskAopImpl.class);
	
	@Resource
	private TaskActionMqSend taskActionMqSend;
	
	/**
	 * 收货地址
	 * @param jp
	 * @param result
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserShippingAddressController.userShippingAddressAdd(..))",returning="result")
	public void doAfterAddress(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			int userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.BIND_ADDRESS.getId();//动作标识（绑定收货地址）
			BigDecimal money = new BigDecimal(0);
			String remark = "绑定收货地址";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doAfterAddress] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	/**
	 * 绑定邮箱
	 * 
	 * @param jp
	 * @param result
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userEmailBind(..))",returning="result")
	public void doAfterBindEmail(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			Integer userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.BIND_EMAIL.getId();//动作标识（绑定收货地址）
			BigDecimal money = new BigDecimal(0);
			String remark = "绑定邮箱";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doAfterBindEmail] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	/**
	 * 绑定手机
	 * @param jp
	 * @param result
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userPhoneBind(..))",returning="result")
	public void doAfterBindPhone(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			Integer userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.BIND_PHONE.getId();//动作标识（绑定收货地址）
			BigDecimal money = new BigDecimal(0);
			String remark = "绑定手机";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doAfterBindPhone] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	/**
	 * 查看常规任务
	 * 
	 * @param jp
	 * @param result
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.TaskController.pointTaskList(..))",returning="result")
	public void doAfterPointTask(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ) {
				return;
			}
			
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			Integer taskId = requestInfo.getIntParameter(ApiUrlParamEnum.taskId.getParamName(), 0);
			if(taskId > 0) {
				return;
			}
			Integer openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			Integer userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			String actionType = TaskActionListEmum.CHECK_POINT_TASK.getId();//动作标识（查看常规任务）
			BigDecimal money = new BigDecimal(0);
			String remark = "查看常规任务";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doAfterPointTask] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	/**
	 * 评价
	 * 
	 * @param jp 切入点
	 * @param result 方法返回值
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.GoodsEvaluateController.batchMerge(..))||"
			+ " execution(* com.frogs.ucenter.v1.controller.GoodsEvaluateController.goodsEvaluateMerge(..))",returning="result")
	public void doAfterEvaluate(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			Integer userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			String orderId = requestInfo.getParameter(ApiUrlParamEnum.orderId.getParamName(), "");
			String buyTime = requestInfo.getParameter(ApiUrlParamEnum.buyTime.getParamName(), "");
			Integer openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.EVALUATE.getId();//动作标识（评价）
			BigDecimal money = new BigDecimal(0);
			String method = jp.getStaticPart().getSignature().getName();
			String remark = "评价";
			if(method.equals("batchMerge")){//如果是批量评价，则需要获取评价条数
				String evaluates = requestInfo.getParameter("evaluates");
				JSONArray array = JSONArray.parseArray(evaluates);
				if (array != null) {
					for (int i = 0; i < array.size(); i++) {
						JSONObject obj = array.getJSONObject(i);
						orderId = obj.getString("orderId");
						buyTime = obj.getString("buyTime");
						taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
						this.addUserIntegral(userId, orderId, buyTime);
					}
				}
			}else{
				taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
				this.addUserIntegral(userId, orderId, buyTime);
			}
		} catch (Exception e) {
			log.error("func[doAfterEvaluate] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userLogin(..))|| "
			+ "execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userLoginNoPw(..))|| "
			+ "execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userOpenPlatformLogin(..))||"
			+ "execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userDynamicPasswordLogin(..))",returning="result")
	public void doAfterLogin(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			if ((JSONObject.parseObject(result.toString())).getJSONObject("userBaseAccountInfo") != null) {
				HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
				HttpRequestInfo requestInfo = new HttpRequestInfo(req);
				Integer openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
				Integer userId = (JSONObject.parseObject(result.toString())).getJSONObject("userBaseAccountInfo").getInteger("id");
				String  actionType = TaskActionListEmum.LOGIN.getId();//动作标识（登录）
				BigDecimal money = new BigDecimal(0);
				String remark = "登录";
				taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
			}
		} catch (Exception e) {
			log.error("func[doAfterLogin] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.userAccountAdd(..))||"
			+ " execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.autoRegister(..))||"
			+ " execution(* com.frogs.ucenter.v1.controller.UserAccountInfoController.bindOpenPlatformLogin(..))",returning="result")
	public void doAfterRegister(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			String method = jp.getStaticPart().getSignature().getName();
			Integer userId = 0;
			Integer isEmailValid = 0;
			Integer isPhoneValid = 0;
			BigDecimal money = new BigDecimal(0);
			String remark = "注册";
			String  actionType = TaskActionListEmum.REGISTER.getId();//动作标识（注册）
			Integer openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			if(method.equals("bindOpenPlatformLogin")){//绑定第三方平台
				int isRegister = requestInfo.getIntParameter("isRegister", 0);
				userId = (JSONObject.parseObject(result.toString())).getJSONObject("userBaseAccountInfo").getInteger("id");
				if(isRegister == UserRegisterTypeEnum.REGISTER_BIND_NEW.getId() || isRegister == UserRegisterTypeEnum.REGISTER_BIND_OPENPLATFOMR.getId()){
					//注册新用户
					isEmailValid = (JSONObject.parseObject(result.toString())).getJSONObject("userBaseAccountInfo").getInteger("isEmailValid");
					isPhoneValid = (JSONObject.parseObject(result.toString())).getJSONObject("userBaseAccountInfo").getInteger("isPhoneValid");
					taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
				}
			}else{
				userId = (JSONObject.parseObject(result.toString())).getJSONObject("info").getInteger("id");
				isEmailValid = (JSONObject.parseObject(result.toString())).getJSONObject("info").getInteger("isEmailValid");
				isPhoneValid = (JSONObject.parseObject(result.toString())).getJSONObject("info").getInteger("isPhoneValid");
				taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
			}
			if(isEmailValid == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()){
				actionType = TaskActionListEmum.BIND_EMAIL.getId();//绑定邮箱注册
				remark = "绑定邮箱";
				taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
			}
			if(isPhoneValid == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()){
				actionType = TaskActionListEmum.BIND_PHONE.getId();//绑定手机注册
				remark = "绑定手机";
				taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
			}
			actionType = TaskActionListEmum.LOGIN.getId();
			remark = "登录";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);

		} catch (Exception e) {
			log.error("func[doAfterReturning] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
	}
	
	/**
	 * 一键提醒测量场景
	 * @param jp 切入点
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserRemindedInfoController.doRemind(..))",returning="result")
	public void doAfterRemind(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			int userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.REMIND_TASK.getId();//动作标识（绑定收货地址）
			BigDecimal money = new BigDecimal(0);
			String remark = "提醒家人测量";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doAfterRemind] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	/**
	 * 点赞场景
	 * @param jp 切入点
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserPraiseInfoController.doPraise(..))",returning="result")
	public void doPraise(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			int userId = requestInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName());
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			String actionType = TaskActionListEmum.PRAISE_TASK.getId();//动作标识
			BigDecimal money = new BigDecimal(0);
			String remark = "点赞成功";
			taskActionMqSend.send(actionType, money, remark, userId, openPlatformId);
		} catch (Exception e) {
			log.error("func[doPraise] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
}
